/*
 * Copyright 2024-2025 Embabel Software, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.embabel.agent.api.common.reference

import com.embabel.agent.api.common.LlmReference
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.fasterxml.jackson.module.kotlin.readValue
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import org.springframework.core.io.DefaultResourceLoader
import org.springframework.core.io.ResourceLoader

/**
 * Parse LlmReferenceProviders from YML files
 */
object LlmReferenceProviders {

    private val yamlMapper = ObjectMapper(YAMLFactory()).registerKotlinModule()

    /**
     * Parse a YML file at the given resource location into a list of LlmReference
     * @param resource Spring resource location of the YML file (supports classpath:, file:, etc.)
     * @param resourceLoader Spring ResourceLoader to use for loading the resource
     */
    @JvmStatic
    @JvmOverloads
    fun fromYmlFile(
        resource: String,
        resourceLoader: ResourceLoader = DefaultResourceLoader(),
    ): List<LlmReference> {
        val springResource = resourceLoader.getResource(resource)
        if (!springResource.exists()) {
            throw IllegalArgumentException("Resource not found: $resource")
        }

        // Parse YAML as list of LlmReferenceProvider
        val providers: List<LlmReferenceProvider> = springResource.inputStream.use { inputStream ->
            yamlMapper.readValue(inputStream)
        }

        // Convert providers to references
        return providers.map { it.reference() }
    }
}
